package com.demo;

import java.io.File;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendEmail {
	
	// 发送邮件
		public boolean   sendMail(int totalCase, int totalPass, int totalError, int totalException, int totalElse, String xlsPath) {
			try {
				Properties props = new Properties();// 存储连接参数
				props.put("mail.smtp.host", "10.101.1.5"); // smtp主机
				props.put("mail.smtp.auth", "true"); // 需要身份验证

				Session session = Session.getInstance(props);
				// 获取一个邮件session
				session.setDebug(true);
				MimeMessage message = new MimeMessage(session); // 邮件会话新建一个邮件信息

				// 检查邮件地址是否合法
				

				// 设置源地址
				// message.setFrom(new InternetAddress(from)); //等价于下面两条代码
				InternetAddress addressFrom = new InternetAddress("lilinxing@csair.com");
				message.setFrom(addressFrom);

				// 设置目的地址
				InternetAddress addressTo = new InternetAddress("lilinxing@csair.com");
				message.setRecipient(Message.RecipientType.TO, addressTo);
				message.setSubject("测试报告");
				// message.setText(content); //邮件正文

				String content="<html>共执行用例："+totalCase+
						"<html/>";
				Multipart mp = new MimeMultipart();// 邮件内容
				MimeBodyPart mbpContent = new MimeBodyPart();
				mbpContent.setContent(content, "text/html"); // 邮件格式

				// 向MimeMessage添加代表正文（Multipart）
				mp.addBodyPart(mbpContent);
				message.setContent(mp);
				
				File xlsFile = new File(xlsPath);
				mbpContent.attachFile(xlsFile);
				//message.setSentDate(new Date()); // 设置发送的时间

				Transport transport = session.getTransport("smtp"); // 设置邮件传输

				transport.connect((String) props.get("mail.smtp.host"), "747227",
						"li!159753"); // 连接主机

				transport.sendMessage(message,
						message.getRecipients(MimeMessage.RecipientType.TO)); // 发送邮件

				System.out.println("Send Success !");

				transport.close(); // 关闭传输

				return true;

			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
}
